package com.mgl.mymusic_demo;

/**
 * Created by Administrator on 2016/3/21.
 */

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MusicService extends Service {
    private int progress = 0;

    private boolean isPause = false;

    public MusicService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent != null){
            int action = intent.getIntExtra("action", -1);
            switch (action) {
                case 1:
                    play();
                    break;
                case 2:
                    pause();
                    break;
                case 3:
                    resume();
                    break;
            }
        }else {
//            System.out.println(" I'm Null");
            new MyBinder();

        }



        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {

        return new MyBinder();
    }

    public class MyBinder extends Binder {
        public int getProgress() {
            return progress;
        }
    }

    public void play() {

        new Thread() {

            @Override
            public void run() {
                synchronized (MusicService.this) {
                    for (int i = 0; i <= 800; i++) {
                        if (isPause) {
                            try {
                                MusicService.this.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        progress++;
                    }
                }
            }
        }.start();
    }

    public void pause() {
        isPause = true;
    }

    public synchronized void resume() {
        isPause = false;
        notify();
    }


}